package com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

import com.mlz.mlzmall.ui.activity.act.main.MyApplication;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @version 1.0
 *          Created by wls_xinghuo on 2015/11/17.
 * @description
 */
public class MyCenterUtils {

    /**
     * 上下文的获取
     *
     * @return
     */
    public static Context getContext() {
        return MyApplication.getContext();
    }

    public static String getPackageName() {
        return getContext().getPackageName();
    }

    public static boolean isHeadDrawableExit(String headDrawablePath) {
        File file = new File(headDrawablePath);
        if (file.exists()) {
            return true;
        } else {
            return false;
        }
    }



    /*
    传入头像id，方便设置默认的头像
     */

    public static Drawable getHeadImageDrawable(Context context, int defaultHeadImageId, String headDrawablePath) {
        if (MyCenterUtils.isHeadDrawableExit(headDrawablePath)) {
            Drawable headImageDrawable = MyCenterUtils.bitmapToDrawable(BitmapFactory.decodeFile(headDrawablePath));
            return headImageDrawable;
        } else {
            return context.getResources().getDrawable(defaultHeadImageId);
        }
    }

    /*
    修改头像后要替代掉之前的头像
     */
    public static boolean saveHeadDrawableLocal(Drawable headDrawable, String headDrawablePath) {

        if (isSDCardAvailable()) {

            initPath(headDrawablePath);

            FileOutputStream b = null;
            Bitmap bitmap = drawableToBitmap(headDrawable);
            try {
                b = new FileOutputStream(headDrawablePath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    //关闭流

                    b.flush();
                    b.close();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return true;
        } else {
            return false;
        }


    }

    public static void upLoadHeadDrawable(Bitmap bitmap, String headDrawableInternetPath) {


    }

    /**
     * convert Drawable to Bitmap
     *
     * @param d
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable d) {
        return d == null ? null : ((BitmapDrawable) d).getBitmap();
    }


    /**
     * convert Bitmap to Drawable
     *
     * @param b
     * @return
     */
    public static Drawable bitmapToDrawable(Bitmap b) {
        return b == null ? null : new BitmapDrawable(b);
    }

    /**
     * 判断SD卡是否挂载
     */
    public static boolean isSDCardAvailable() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkAvailable(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {

            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /*
    是否处于wifi环境中
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }

        return false;
    }

    /*
    创建指定的路径
     */
    public static void initPath(String path) {

        File f = new File(path);
        if (!f.exists()) {
            // 创建父路径
            String parentPath = f.getParent();
            File parentFile = new File(parentPath);
            if (parentFile.exists()) {
            } else {
                parentFile.mkdirs();
            }
            // 创建文件
            try {
                System.out.println("create");
                f.createNewFile();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {

        }

    }

    public static Calendar string2Calendar(String strDate) {
        Date date = new Date();

        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (!TextUtils.isEmpty(strDate))
                date = df.parse(strDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c;
    }



    public static void LogText(String content) {
        Log.i("exiu-wls-log", content);
//        Log.i("wls-text", content);
//        Log.i("wls-text", content);
//        Log.i("wls-text", content);
    }

    public static void LogTextWithPlace(Class t, String content) {
        Log.i("exiu-wls-log", content + "，位于类:" + t.getName());
    }

    public static void ToastText(String content) {
        Toast.makeText(MyApplication.getContext(), content, Toast.LENGTH_SHORT).show();
    }
    public static void ToastText(int stringid) {
        Toast.makeText(MyApplication.getContext(), getContext().getResources().getString(stringid), Toast.LENGTH_SHORT).show();
    }



    /*
    显示到界面时候将手机号码加密
     */
    public static String repalcePhoneNumWithStars(String phoneNum) {

        String backnum = phoneNum;
        try {

            backnum = phoneNum.substring(0, 3) + "****" + phoneNum.substring(7);

        } catch (Exception e) {
            System.out.println("may be the string param isn't a phonenum");
            throw e;
        }
        return backnum;
    }


    // 版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    // 版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static int getScreenWidth(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;//宽度height = dm.heightPixels ;
    }

    public static int getScreenHeight(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * @param dip
     * @return
     */
    public static int dip2px(int dip) {
        // 公式 1: px = dp * (dpi / 160)
        // 公式 2: dp = px / denistity;
        DisplayMetrics metrics = new DisplayMetrics();
        ;
        float density = metrics.density;
        // metrics.densityDpi
        return (int) (dip * density + 0.5f);
    }

    public static int px2dip(int px) {
        // 公式 1: px = dp * (dpi / 160)
        // 公式 2: dp = px / denistity;
        DisplayMetrics metrics = new DisplayMetrics();
        float density = metrics.density;
        // metrics.densityDpi
        return (int) (px / density + 0.5f);
    }


    /*
    服务器状态返回
     */
    public static String getServiceResponseStatus(String s) {

        try {
            JSONObject jsonObject = new JSONObject(s);
            String result = jsonObject.getString("result");
            if ("1".equals(result)) {
                //成功的标志
                return "1";
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "0";//解析出错或者服务器出错
    }
}
